package com.example.ktapplication.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.ktapplication.R
import com.example.ktapplication.adapter.HeaderBottomAdapter
import com.example.ktapplication.bean.ArticleDataX
import com.example.ktapplication.bean.CustomViewsInfo
import com.example.ktapplication.databinding.HomeBannerLayoutBinding
import com.example.ktapplication.enum.StateLayoutMode
import com.example.ktapplication.model.ArticleViewModel
import com.example.ktapplication.model.BannerViewModel
import com.example.ktapplication.model.SystemViewModel
import com.example.ktapplication.state.ArticleState
import com.example.ktapplication.state.HomeBannerState
import com.example.ktapplication.utils.event.Event
import com.example.ktapplication.utils.event.EventBusUtil
import com.example.ktapplication.utils.jumpUrl
import com.example.ktapplication.view.CustomTitleBar
import com.example.ktapplication.view.StatusLayout
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.eventbus.Subscribe
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class HomeFragment : Fragment(), OnClickListener {

    lateinit var binding: HomeBannerLayoutBinding

    companion object {
        private var instance: HomeFragment? = null

        fun getInstance(): HomeFragment {
            if (instance == null) {
                instance = HomeFragment()
            }
            return instance!!
        }
    }

    private lateinit var titleBar: CustomTitleBar
    private lateinit var imgFind: ImageView
    private lateinit var imgMenu: ImageView
    private lateinit var txtTitle: TextView

    private lateinit var mStatusLayout: StatusLayout
    var mHomeContainer: View? = null
    private lateinit var loadingView: View
    private lateinit var emptyView: View
    private lateinit var errorView: View
    private lateinit var netView: View

    private lateinit var mRecyclerView: RecyclerView
    private lateinit var adapter: HeaderBottomAdapter
    var bannerList = ArrayList<CustomViewsInfo>()
    var articleList = ArrayList<ArticleDataX>()


    private lateinit var mRefresh: SmartRefreshLayout
    var isLoadMore: Boolean = false
    var type: StateLayoutMode? = null

    private var bannerJob: Job? = null
    private var aritcleJob: Job? = null
    private lateinit var bannerModel: BannerViewModel
    private var page: Int = 0
    private lateinit var articleViewModel: ArticleViewModel

    private val viewModel by lazy {
        ViewModelProvider(this)[SystemViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // 返回你的布局或视图
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ///初始化组件
        bannerModel = ViewModelProvider(this)[BannerViewModel::class.java]
        articleViewModel = ViewModelProvider(this)[ArticleViewModel::class.java]
        initView(view)
        EventBusUtil.eventBus.register(this)
    }

    fun initView(view: View) {
        mRefresh = view.findViewById(R.id.smartRefreshLayout)
        titleBar = view.findViewById<CustomTitleBar>(R.id.titleBar)
        imgFind = titleBar.findViewById<ImageView>(R.id.img_find)
        imgMenu = titleBar.findViewById<ImageView>(R.id.img_menu)
        txtTitle = titleBar.findViewById<TextView>(R.id.txt_title)
        txtTitle.text = "首页"
        initStatusLayou(view)
        initEvent()
        waithData()
        initData(false)
    }

    @Subscribe
    fun onHomeClick(event: Event.HomeClick) { //首页点击事件
        event.tag.let {
            if (it == "ERROR") {
                initData(true)
            } else {

            }
        }
    }

    private fun waithData() {
        bannerJob = lifecycleScope.launch(Dispatchers.IO) {
            ///IO线程
            bannerModel.state.collect { state ->
                when (state) {
                    is HomeBannerState.OnSuccess -> {
                        if (state.banner != null) {
                            if (state.banner!!.errorCode == 0) {
                                if (state.banner!!.data.isEmpty()) {
                                    type = StateLayoutMode.EMPTY
                                    showErroeView(type!!)
                                } else {
                                    bannerList.clear()
                                    val data = state!!.banner!!.data
                                    for (item in data) {
                                        val url = item.imagePath
                                        val content = item.title
                                        val viewInfo = CustomViewsInfo(url, content)
                                        bannerList.add(viewInfo)
                                    }
                                    articleViewModel.getHomeAritcleData(page)
                                    page++
                                }
                            } else {
                                type = StateLayoutMode.ERROR
                                showErroeView(type!!)
                            }
                            state.banner!!.count += 1
                        }
                    }

                    is HomeBannerState.OnError -> {
                        val error = state.exception!!.message
                        type = StateLayoutMode.ERROR
                        showErroeView(type!!)
                    }
                }
            }
        }
        aritcleJob = lifecycleScope.launch(Dispatchers.IO) {
            ///IO线程
            articleViewModel.state.collect { state ->
                when (state) {
                    is ArticleState.OnSuccess -> {
                        if (state.article != null) {
                            if (state.article!!.errorCode == 0) {
                                if (state.article!!.data.datas.isEmpty()) {
                                    type = StateLayoutMode.EMPTY
                                    showErroeView(type!!)
                                } else {
                                    if (isLoadMore) {
                                        articleList.addAll(state.article!!.data.datas)
                                        withContext(Dispatchers.Main) {
                                            adapter.setData(bannerList, articleList)
                                        }
                                    } else {
                                        articleList.clear()
                                        articleList.addAll(state.article!!.data.datas)
                                        withContext(Dispatchers.Main) {
                                            mRefresh.finishRefresh()
                                            initHomeContainer()
                                            mStatusLayout.addView(mHomeContainer!!)
                                            mStatusLayout.setMode(StateLayoutMode.CONTENT)
                                        }
                                    }
                                }
                            } else {
                                type = StateLayoutMode.ERROR
                                showErroeView(type!!)
                            }
                            state.article!!.count += 1
                        }
                    }

                    is ArticleState.OnError -> {
                        val error = state.exception!!.message;
                        type = StateLayoutMode.ERROR
                        showErroeView(type!!)
                    }
                }
            }
        }
    }

    fun initHomeContainer() {
        mHomeContainer = layoutInflater.inflate(R.layout.fragment_home_container, null)
        mRecyclerView = mHomeContainer!!.findViewById<RecyclerView>(R.id.homeRecyclerView)
        mRecyclerView.layoutManager = LinearLayoutManager(this.activity)
        adapter = HeaderBottomAdapter(this.activity)
        adapter.setItemClickListener(object : HeaderBottomAdapter.OnItemClickListener {
            override fun onCollectClick(item: ArticleDataX) {
                val id = item.id
                if (item.collect) {
                    viewModel.unCollect(id) {
                        adapter.updateItem(item.apply { collect = false })
                    }
                } else {
                    viewModel.collect(id) {
                        adapter.updateItem(item.apply { collect = true })
                    }
                }
            }

            override fun onBodyClick(item: ArticleDataX) {
                item.let {
                    requireActivity().jumpUrl(it.link, it.title)
                }
            }
        })
        adapter.setData(bannerList, articleList)
        mRecyclerView.adapter = adapter
        adapter.notifyDataSetChanged()
    }

    ///加载数据
    private fun initData(isRefresh: Boolean) {
        lifecycleScope.launch(Dispatchers.IO) {
            bannerModel.getHomeBannerData()
        }
    }


    private fun initStatusLayou(view: View) {
        mStatusLayout = view.findViewById<StatusLayout>(R.id.statusLayout)
        loadingView = layoutInflater.inflate(R.layout.status_layout_loading, null)
        mStatusLayout.setLoadingLayout(loadingView)
        emptyView = layoutInflater.inflate(R.layout.status_layout_empty, null)
        mStatusLayout.setEmptyLayout(emptyView)
        errorView = layoutInflater.inflate(R.layout.status_layout_error, null)
        mStatusLayout.setErrorLayout(errorView);
        netView = layoutInflater.inflate(R.layout.status_layout_net, null)
        mStatusLayout.setNetLayout(netView)
        emptyView.findViewById<LinearLayout>(R.id.btn_empty).setOnClickListener(this);
        errorView.findViewById<LinearLayout>(R.id.btn_error).setOnClickListener(this);
        mStatusLayout.setMode(StateLayoutMode.LOADING);
    }

    private fun initEvent() {
        imgFind.setOnClickListener {
            EventBusUtil.eventBus.post(Event.MainClickFind());
        }
        imgMenu.setOnClickListener {
            EventBusUtil.eventBus.post(Event.MainClickMenu())
        }
        //上拉加载
        mRefresh.setOnLoadMoreListener(object : OnLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                articleViewModel.getHomeAritcleData(page)
                page++
                refreshLayout.finishLoadMore()
            }
        })
        //下拉刷新
        mRefresh.setOnRefreshListener(object : OnRefreshListener {

            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 0
                isLoadMore = false
                initData(true)
            }
        })
    }

    private fun showErroeView(type: StateLayoutMode) {
        lifecycleScope.launch(Dispatchers.Main) {
            mRefresh.finishRefresh()
            mStatusLayout.setMode(type)
        }
    }

    override fun onClick(v: View) {

    }

    override fun onDestroy() {
        bannerJob!!.cancel()
        super.onDestroy()
        EventBusUtil.eventBus.unregister(this)
    }
}
